﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;

namespace IrisGenerator.Common.UI.XmlConfiguration
{
    public class XmlConfigFileReader
    {

        public static string ConfigFilePath { get; set; }
        
        private static XElement GetSpecificObjectNode(XElement rootNode,string objectName)
        {
            if(rootNode==null || string.IsNullOrEmpty(objectName))
                return null;

            var dbQuery=from node in rootNode.Descendants("Control")
                        where node.Attribute("name").Value==objectName
                        select node;

            if (dbQuery.Count()>1)
                throw new ApplicationException("The config section for " + objectName +
                    " appears more than once.");

            if (dbQuery.Count()==1)
                return dbQuery.ElementAt(0);

            return null;

        }

        public static void LoadConfiguration(Control ctrl)
        {
            if (string.IsNullOrEmpty(ConfigFilePath))
                return;

            var db = System.Xml.Linq.XElement.Load(ConfigFilePath);
            if (db == null)
                return;

            XElement controlNode=GetSpecificObjectNode(db,ctrl.Name);

            if (controlNode==null)
                return;

            LoadControl(controlNode,ctrl);
        }

        private static void LoadControl(XElement rootNode,Control ctrl)
        {
            string ControlType = rootNode.Attribute("type").Value;

            switch (ControlType)
            {
                case "DataGrid":
                    XmlDatagridConfiguration dgConfig = new XmlDatagridConfiguration();
                    dgConfig.LoadConfiguration(rootNode, ctrl);
                    break;
                case "List":
                    XmlListConfiguration listConfig = new XmlListConfiguration();
                    listConfig.LoadConfiguration(rootNode, ctrl);
                    break;
                default:
                    XmlConfiguration.XmlToObject(rootNode,ctrl);
                    break;
            }
        }
    }
}
